"""
云端存储控制器文件
处理原始数据传送到云端存储服务的HTTP请求
使用FastAPI的APIRouter定义路由，调用云端API服务处理数据传送
原理：作为原始数据传送的API入口点，负责接收平板端数据并转发给云端存储服务
"""

from fastapi import APIRouter, HTTPException, Depends, BackgroundTasks
from pydantic import BaseModel, Field
from typing import List, Optional
from datetime import datetime
import logging

from ..models.cloud_storage_models import (
    TabletRawData, 
    CloudStorageResponse, 
    RealtimeDataRequest, 
    RealtimeDataResponse,
    RealtimeDataPoint
)
from ..service.cloud_api import get_cloud_api_service, CloudAPIService
from ..utils.response import success_response, error_response, ResponseCode

# 配置日志
logger = logging.getLogger(__name__)

# 创建路由器
cloud_storage_router = APIRouter(prefix="/cloud-storage", tags=["云端存储"])

# 请求模型
class RawDataUploadRequest(BaseModel):
    """原始数据上传请求模型"""
    data_list: List[TabletRawData] = Field(..., description="平板端原始数据列表（10-15秒的数据）")
    
    class Config:
        schema_extra = {
            "example": {
                "data_list": [
                    {
                        "session_id": 12345,
                        "room_id": "room_001",
                        "timestamp": 1699123456789,
                        "raw_data": [  # 修改字段名从raw_value到raw_data
                            {"timestamp": 1699123456789, "value": 123.45},
                            {"timestamp": 1699123456791, "value": 124.56}
                        ],
                        "delta": 15.2,
                        "theta": 25.8,
                        "low_alpha": 18.5,
                        "high_alpha": 22.3,
                        "low_beta": 12.7,
                        "high_beta": 8.9,
                        "low_gamma": 5.4,
                        "mid_gamma": 3.2,
                        "attention": 75,
                        "meditation": 68,
                        "signal_quality": 85,
                        "blink_strength": 12
                    }
                ]
            }
        }


class RealtimeDataUploadRequest(BaseModel):
    """实时数据上传请求模型"""
    session_id: str = Field(..., description="会话ID")
    realtime_data: RealtimeDataRequest = Field(..., description="实时数据请求对象")
    
    class Config:
        schema_extra = {
            "example": {
                "session_id": "12345",
                "realtime_data": {
                    "room_id": "room_001",
                    "data_points": [
                        {
                            "timestamp": 1699123456,
                            "delta_ratio": 0.15,
                            "theta_ratio": 0.25,
                            "low_alpha_ratio": 0.18,
                            "high_alpha_ratio": 0.22,
                            "low_beta_ratio": 0.12,
                            "high_beta_ratio": 0.08,
                            "low_gamma_ratio": 0.05,
                            "mid_gamma_ratio": 0.03,
                            "state": "awake",
                            "confidence": 0.85
                        }
                    ]
                }
            }
        }


class RealtimeDataUploadResponse(BaseModel):
    """实时数据上传响应模型"""
    success: bool = Field(True, description="是否成功")
    message: str = Field("实时数据发送成功", description="响应消息")
    uploaded_data_points: int = Field(..., description="上传的数据点数量")
    session_id: str = Field(..., description="会话ID")
    timestamp: int = Field(..., description="响应时间戳")
    cloud_storage_response: Optional[RealtimeDataResponse] = Field(None, description="云端存储服务响应")
    data: Optional[dict] = Field(None, description="额外数据")


# 响应模型
class RawDataUploadResponse(BaseModel):
    """原始数据上传响应模型"""
    success: bool = Field(True, description="是否成功")
    message: str = Field("数据传送成功", description="响应消息")
    uploaded_data_points: int = Field(..., description="上传的数据点数量")
    session_id: int = Field(..., description="会话ID")
    timestamp: int = Field(..., description="响应时间戳")
    cloud_storage_response: Optional[CloudStorageResponse] = Field(None, description="云端存储服务响应")
    data: Optional[dict] = Field(None, description="额外数据")

@cloud_storage_router.post(
    "/upload-raw-data",
    response_model=RawDataUploadResponse,
    summary="上传原始数据到云端存储",
    description="将平板端的原始脑波数据（10-15秒批量）传送到云端存储服务"
)
async def upload_raw_data_to_cloud_storage(
    request: RawDataUploadRequest,
    background_tasks: BackgroundTasks,
    cloud_api_service: CloudAPIService = Depends(get_cloud_api_service)
):
    """
    上传原始数据到云端存储接口
    
    Args:
        request: 原始数据上传请求
        background_tasks: 后台任务
        cloud_api_service: 云端API服务实例
    
    Returns:
        上传结果响应
    """
    try:
        logger.info(f"开始上传原始数据到云端存储，数据包数量: {len(request.data_list)}")
        
        # 验证数据
        if not request.data_list:
            raise HTTPException(status_code=400, detail="数据列表不能为空")
        
        # 计算总数据点数量
        total_data_points = sum(len(data.raw_data) for data in request.data_list)  # 修改从raw_value到raw_data
        session_id = request.data_list[0].session_id
        
        # 同步上传数据到云端存储服务
        cloud_response = cloud_api_service.upload_raw_data_to_cloud_storage(request.data_list)
        
        if cloud_response and cloud_response.success:
            logger.info(f"原始数据上传成功: session_id={session_id}, 数据点数量={total_data_points}")
            
            return RawDataUploadResponse(
                success=True,
                message="数据传送成功",
                uploaded_data_points=total_data_points,
                session_id=session_id,
                timestamp=int(datetime.now().timestamp() * 1000),
                cloud_storage_response=cloud_response
            )
        else:
            error_msg = cloud_response.message if cloud_response else "云端存储服务无响应"
            logger.error(f"原始数据上传失败: session_id={session_id}, 错误={error_msg}")
            
            return RawDataUploadResponse(
                success=False,
                message=f"数据传送失败: {error_msg}",
                uploaded_data_points=0,
                session_id=session_id,
                timestamp=int(datetime.now().timestamp() * 1000),
                cloud_storage_response=cloud_response,
                data={
                    "session_id": session_id,
                    "uploaded_data_points": 0
                }
            )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"上传原始数据异常: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"服务器内部错误: {str(e)}")

# 缺失的模型定义
class CloudUploadResponse(BaseModel):
    """云端上传响应模型"""
    success: bool = Field(True, description="是否成功")
    message: str = Field("上传成功", description="响应消息")
    upload_id: str = Field(..., description="云端存储ID")
    cloud_url: str = Field(..., description="云端存储URL")
    timestamp: int = Field(..., description="响应时间戳")
    data_size: int = Field(..., description="数据大小（字节）")

class CloudRawDataRequest(BaseModel):
    """云端原始数据上传请求模型"""
    session_id: str = Field(..., description="会话ID")
    room_id: str = Field(..., description="房间ID")
    timestamp: int = Field(..., description="时间戳")
    raw_data: List[dict] = Field(..., description="原始脑波数据")
    metadata: Optional[dict] = Field(None, description="元数据")

class CloudRealtimeDataRequest(BaseModel):
    """云端实时分析数据上传请求模型"""
    session_id: str = Field(..., description="会话ID")
    room_id: str = Field(..., description="房间ID")
    timestamp: int = Field(..., description="时间戳")
    sleep_stage: str = Field(..., description="睡眠阶段")
    confidence: float = Field(..., description="置信度")
    frequency_bands: Optional[dict] = Field(None, description="频段数据")
    metadata: Optional[dict] = Field(None, description="元数据")

class CloudStorageStatusResponse(BaseModel):
    """云端存储服务状态响应模型"""
    status: str = Field(..., description="服务状态")
    message: str = Field(..., description="状态消息")
    timestamp: int = Field(..., description="响应时间戳")
    service_available: bool = Field(..., description="服务是否可用")
    storage_quota_used: float = Field(..., description="存储使用率")
    storage_quota_total: int = Field(..., description="总存储空间")
    last_backup_time: int = Field(..., description="最后备份时间")

@cloud_storage_router.get(
    "/status",
    summary="获取云端存储服务状态",
    description="检查云端存储服务的连接状态和配置信息"
)
async def get_cloud_storage_status(
    cloud_api_service: CloudAPIService = Depends(get_cloud_api_service)
):
    """
    获取云端存储服务状态接口
    
    Args:
        cloud_api_service: 云端API服务实例
    
    Returns:
        云端存储服务状态信息
    """
    try:
        status_info = {
            "cloud_storage_base_url": cloud_api_service.cloud_storage_base_url,
            "raw_data_upload_endpoint": cloud_api_service.raw_data_upload_endpoint,
            "upload_timeout": cloud_api_service.raw_data_upload_timeout,
            "status": "configured",
            "timestamp": int(datetime.now().timestamp() * 1000)
        }
        
        return {
            "success": True,
            "message": "云端存储服务状态获取成功",
            "data": status_info
        }
        
    except Exception as e:
        logger.error(f"获取云端存储服务状态异常: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"服务器内部错误: {str(e)}")